import { createRouter, createWebHashHistory } from 'vue-router'
import {IRouter, IScrollBehavior} from '@/interface'
import constantRoutes from "@/router/constantRoutes"
import asyncRoutes from "@/router/asyncRoutes"
import errRoutes from "@/router/errRoutes"
import { storeState } from "@/store/tools"

const routes:IRouter = [...constantRoutes, ...asyncRoutes, ...errRoutes]

const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior: ((to, from, savedPosition) => (savedPosition || { x: 0, y: 0 })) as IScrollBehavior,
  routes,
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title as string
  if (localStorage.getItem('token')) {
    // 已登录
    if (to.path === '/login') {
      next()
    } else {
      if (!to.meta.view) return next()
      // 自定义权限项
      if ((to.meta.view as Array<string>).indexOf(storeState.userInfo.type) !== -1) {
        next()
      } else next(false)
    }
  } else {
    // 未登录
    const whiteRoutes = [...constantRoutes, ...errRoutes]
    for (let index in whiteRoutes) {
      if (to.path === whiteRoutes[index].path) {
        next()
        break
      } else {
        if (+index === whiteRoutes.length - 1) {
          next({ path: '/login' })
          break
        }
      }
    }
  }
})

export default router
